<?php

namespace app\admin\controller;

use app\client\api\C_goods;
use app\client\admin\C_plugin;
use app\client\common\C_appStore;

class  AppStore
{

    public $c_goods;
    public $c_plugin;
    public $c_appStore;

    /**
     * @menuName 软件商店
     * 上面的是菜单的名字
     * @moduleName 软件列表
     * 上面的是控制器的名字
     */
    public function __construct()
    {
        $this->c_goods = new C_goods();
        $this->c_plugin = new C_plugin();
        $this->c_appStore = new C_appStore();
    }

    /**
     * @actionName  插件列表
     * @show 1
     */
    public function index()
    {
        $plugin_ids=app("L_Common_appStore")->getPluginId();
        $authData=array(
            "appStore_install"=>\Authorize_event::checkAuth('app\admin\controller\AppStore',"install"),
        );
        $installed=request()->param("installed",0);
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "url" => config("app.url"),
        );
        if($installed){
            $response = $this->c_goods->installedPlugin($paramsObj);
            $listData = array();
            if ($response["success"]) {
                $listData = $response["data"];
            }
        }else{
            $response = $this->c_goods->goodList($paramsObj);
            $listData = array();
            if ($response["success"]) {
                $listData = $response["data"];
            }
        }

        $response = $this->c_goods->pluginCategory();
        $category = array();
        if ($response["success"]) {
            $category = $response["data"];
        }

        $data = array();
        $data["authData"] = $authData;
        $data["listData"] = $listData;
        $data["category"] = $category;
        $data["plugin_ids"] = $plugin_ids;
        $data["request"] = request()->param();
        return view("admin/appStore/index", $data);
    }

    /**
     * @actionName  安装
     * @show 2
     */
    public function install()
    {
        $pluginId = request()->param("pluginId");
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "id" => $pluginId,
        );
        $result = $this->c_goods->pluginInfo($paramsObj);
        $download = array();
        $depend = array();
        if ($result["success"]) {
            $rowData = $result["data"];
            $download[]=array(
                "fileSizeFormat"=>app("yifangFormat")->byte(fileInfo($rowData['downUrl'], "content-length")),
                "downUrl"=>$rowData['downUrl'],
                "id"=>$rowData['id'],
                "pluginDir"=>$rowData['pluginDir'],
            );
            if($rowData["depend"]){
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => explode(",",$rowData["depend"]),
                );
                $depend_result = $this->c_goods->pluginInfoById($paramsObj);
                if($depend_result["success"]){
                    $depend_data=$depend_result["data"];
                    foreach($depend_data as $dval){
                        $depend[]=array(
                            "fileSizeFormat"=>app("yifangFormat")->byte(fileInfo($dval['downUrl'], "content-length")),
                            "downUrl"=>$dval['downUrl'],
                            "id"=>$dval['id'],
                            "pluginDir"=>$dval['pluginDir'],
                        );
                    }
                }
            }
        }

        $data = array();
        $data["download"] = $download;
        $data["depend"] = $depend;
        $data["request"] = request()->param();
        return view("admin/appStore/install", $data);
    }

    /**
     * @actionName  执行安装
     * @show 2
     */
    public function run()
    {
        $step = request()->param("step");
        if ($step == "1") {
            return $this->pluginDetail();
        } else if ($step == "2") {
            return $this->install();
        } else {
            return $this->download();
        }
    }

    /**
     * @actionName  下载文件-页面
     * @show 2
     */
    public function download()
    {
        $pluginId = request()->param("pluginId");
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "id" => $pluginId,
        );
        $result = $this->c_goods->pluginInfo($paramsObj);
        $download = array();
        $depend = array();
        if ($result["success"]) {
            $rowData = $result["data"];
            $download[]=array(
                "fileSizeFormat"=>app("yifangFormat")->byte(fileInfo($rowData['downUrl'], "content-length")),
                "downUrl"=>$rowData['downUrl'],
                "id"=>$rowData['id'],
            );
            if($rowData["depend"]){
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => explode(",",$rowData["depend"]),
                );
                $depend_result = $this->c_goods->pluginInfoById($paramsObj);
                if($depend_result["success"]){
                    $depend_data=$depend_result["data"];
                    foreach($depend_data as $dval){
                        $depend[]=array(
                            "fileSizeFormat"=>app("yifangFormat")->byte(fileInfo($dval['downUrl'], "content-length")),
                            "downUrl"=>$dval['downUrl'],
                            "id"=>$dval['id'],
                        );
                    }
                }
            }
        }
        $data = array();
        $data["download"] = $download;
        $data["depend"] = $depend;
        $data["request"] = request()->param();
        return view("admin/appStore/download", $data);
    }

    /**
     * @actionName  插件详情
     * @show 2
     */
    public function pluginDetail()
    {
        $pluginId = request()->param("pluginId");
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "id" => $pluginId,
            "field" => "id,`name`,downUrl,pluginDir,`desc`",
            "format" => 1,
        );
        $result = $this->c_goods->pluginInfo($paramsObj);
        $rowData = array();
        if ($result["success"]) {
            $rowData = $result["data"];
            $rowData['fileSize'] = fileInfo($rowData['downUrl'], "content-length");
            $rowData['fileSizeFormat'] = app("yifangFormat")->byte($rowData['fileSize']);
        }
        $data = array();
        $data["rowData"] = $rowData;
        $data["request"] = request()->param();
        return view("admin/appStore/pluginDetail", $data);
    }

    /**
     * @actionName  系统登录
     * @show 2
     */
    public function yifangLogin()
    {
        //获取登录页面地址
        $referer=request()->param("referer","")?request()->param("referer"):(isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:config("app.url")); //获取来源url
        $paramsObj=paramsObj();
        $paramsObj->params=array(
            "extraData"=>array(
                "scope"=>"snsapi_userinfo",
                "redirect_uri"=>$referer,
            ),
        );
        $checkResult=app("P_oauth_yifang_plugin")->getLoginUrl($paramsObj);
        $loginUrl="";
        if($checkResult["error_no"]==0){
            $loginUrl=$checkResult["result"]["loginUrl"];
        }
        $data = array();
        $data["loginUrl"] = $loginUrl;
        $data["request"] = request()->param();
        return view("admin/appStore/yifang_login", $data);
    }

    /**
     * @actionName  登录回调
     * @show 2
     */
    public function callback()
    {
        $param=request()->param();
        parse_str($param["state"],$stateMap);
        $redirect_uri=isset($stateMap["redirect_uri"])?$stateMap["redirect_uri"]:"";
        $paramsObj=paramsObj();
        $paramsObj->params=array(
            "extraData"=>array(
                "code"=>$param["code"],
            ),
        );
        $checkResult=app("P_oauth_yifang_plugin")->callback($paramsObj);
        if($checkResult["error_no"]==0){
            $result=$checkResult["result"];
            //写入文件
            $runtime=runtimePath();
            $loginFile=$runtime."login_file";
            $users=array();
            $users["guid"]=$result["userInfo"]["guid"];
            $users["nickname"]=$result["userInfo"]["nickname"];
            $users["token"]=$result["accessToken"]["token"];
            $users["userAvatar"]=$result["userInfo"]["userAvatar"];
            file_put_contents($loginFile,toJsonEncode($users));
            if($redirect_uri){
                header("content-type:text/html;charset=utf-8");
                if(strpos($redirect_uri,"/users/callback") === false){
                    //跳转页面
                    $script=<<<EOV
<script>window.top.location.reload();</script>
EOV;
                    echo $script;
                    exit;
                }else{
                    $url=config("app.url");
                    $script=<<<EOV
    "<script>window.top.location.href='{$url}';</script>"
EOV;
                    echo $script;
                    exit;
                }
            }
        }else{
            echo "登录失败";
            exit;
        }
    }

    /**
     * @actionName  使用激活码
     * @show 2
     */
    public function usedByCardName()
    {
        $data = array();
        $data["host"]=parse_url(config("app.url"), PHP_URL_HOST);
        $data["request"] = request()->param();
        return view("admin/appStore/usedByCardName", $data);
    }

    /**
     * @actionName  使用激活码[执行]
     * @show 2
     */
    public function usedByCardNameDo()
    {
        $result = $this->c_appStore->usedByCardName();
        return jsonResponse($result);
    }

    /**
     * @actionName  下载文件[执行]
     * @show 2
     */
    public function downloadFile()
    {
        $result = $this->c_appStore->downloadFile();
        return jsonResponse($result);
    }

    /**
     * 插件安装[执行]
     */
    public function installHandle()
    {
        $result=app("C_Common_appStore")->install();
        return jsonResponse($result);
    }

    /**
     * 插件安装[执行]
     */
    public function pluginInstall()
    {
        $result=app("C_Common_appStore")->pluginInstall();
        return jsonResponse($result);
    }

    /**
     * @actionName  安装[执行]
     * @show 2
     */
    public function installExec()
    {
        continueExec();
        $this->c_appStore->install();
    }

    /**
     * @actionName  卸载[执行]
     * @show 2
     */
    public function uninstallExec()
    {
        $result = $this->c_appStore->uninstall();
        return jsonResponse($result);
    }

    /**
     * @actionName  插件设置
     * @show 2
     */
    public function setUpView()
    {
        $result = $this->c_appStore->setUpView();
        return $result;
    }
}